requirejs.config({
    paths: {
        g2plot: "/assets/addons/health/libs/g2plot"
    }
});
define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'g2plot'], function ($, undefined, Backend, Table, Form, G2Plot) {
    const {Column, RingProgress, Pie, measureTextWidth, WordCloud} = G2Plot;

    function renderStatistic(containerWidth, text, style) {
        const textWidth = measureTextWidth(text, style);
        const textHeight = style.lineHeight || style.fontSize
        const R = containerWidth / 2;
        // r^2 = (w / 2)^2 + (h - offsetY)^2
        let scale = 1;
        if (containerWidth < textWidth) {
            scale = Math.min(Math.sqrt(Math.abs(Math.pow(R, 2) / (Math.pow(textWidth / 2, 2) + Math.pow(textHeight, 2)))), 1);
        }
        const textStyleStr = `width:${containerWidth}px;`;
        return `<div style="${textStyleStr};font-size:${scale}em;line-height:${scale < 1 ? 1 : 'inherit'};">${text}</div>`;
    }

    const Controller = {
        index: () => {
            new Vue({
                el: '#trackingUserRemainIndex',
                data() {
                    return {
                        data: '',
                    }
                },
                mounted() {
                    this.getPageData()
                    this.getUserChannel()
                },
                methods: {
                    getPageData() {
                        let that = this;
                        Fast.api.ajax({
                            url    : 'health/tracking/user_remain/index',
                            loading: false,
                            type   : 'post',
                        }, function (res) {
                            that.data = res
                            that.getRemainColumn(res.days_column)
                            that.ringProgressRender('userAuthPercent', res.user_auth_percent)
                            return false;
                        })
                    },
                    getUserChannel() {
                        let that = this;
                        Fast.api.ajax({
                            url    : 'health/tracking/user_remain/channel',
                            loading: false,
                            type   : 'post',
                        }, function (res) {
                            that.userChannelRender(res.channel)
                            that.userAreaWordCloud(res.area)
                            return false;
                        })
                    },
                    userAreaWordCloud(data) {
                        $('#user-area').empty();
                        const wordCloud = new WordCloud('user-area', {
                            data,
                            height     : 255,
                            wordField  : 'name',
                            weightField: 'value',
                            colorField : 'name',
                            wordStyle  : {
                                fontFamily: 'Verdana',
                                fontSize  : [16, 32],
                                rotation  : 0,
                            },
                            random     : () => 0.5,
                        });

                        wordCloud.render();
                    },
                    userChannelRender(data) {
                        $('#user-channel').empty();
                        const piePlot = new Pie('user-channel', {
                            height       : 250,
                            width        : 250,
                            appendPadding: 10,
                            data,
                            angleField   : 'total',
                            colorField   : 'channel_name',
                            radius       : 1,
                            innerRadius  : 0.64,
                            meta         : {
                                value: {
                                    formatter: (v) => `${v}`,
                                },
                            },
                            label        : {
                                type      : 'inner',
                                offset    : '-50%',
                                autoRotate: false,
                                style     : {textAlign: 'center'},
                                formatter : ({percent}) => `${(percent * 100).toFixed(0)}%`,
                            },
                            statistic    : {
                                title  : {
                                    offsetY   : -8,
                                    customHtml: (container, view, datum) => {
                                        const {width, height} = container.getBoundingClientRect();
                                        const d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2));
                                        const text = datum ? datum.channel_name : '总计';
                                        return renderStatistic(d, text, {fontSize: 28});
                                    },
                                },
                                content: {
                                    offsetY: -4,
                                },
                            },
                            // 添加 中心统计文本 交互
                            interactions: [
                                {type: 'element-selected'},
                                {type: 'element-active'},
                                {
                                    type: 'pie-statistic-active',
                                    cfg : {
                                        start: [
                                            {trigger: 'element:mouseenter', action: 'pie-statistic:change'},
                                            {trigger: 'legend-item:mouseenter', action: 'pie-statistic:change'},
                                        ],
                                        end  : [
                                            {trigger: 'element:mouseleave', action: 'pie-statistic:reset'},
                                            {trigger: 'legend-item:mouseleave', action: 'pie-statistic:reset'},
                                        ],
                                    },
                                },
                            ],
                        });
                        piePlot.render();
                    },
                    /**
                     * 进度圆环
                     * @param container
                     * @param percent
                     */
                    ringProgressRender(container, percent) {
                        $('#' + container).empty();
                        const ringProgress = new RingProgress(container, {
                            height : 200,
                            width  : 200,
                            autoFit: false,
                            percent: percent,
                            color  : ['#5B8FF9', '#E8EDF3'],
                        });
                        ringProgress.render();
                    },
                    getRemainColumn(data) {
                        let that = this;
                        $('#container').empty()
                        const columnPlot = new Column('container', {
                            data,
                            xField: 'day',
                            yField: 'total',
                            label : {
                                // 可手动配置 label 数据标签位置
                                position: 'middle', // 'top', 'bottom', 'middle',
                                // 配置样式
                                style: {
                                    fill   : '#FFFFFF',
                                    opacity: 0.6,
                                },
                            },
                            xAxis : {
                                label: {
                                    autoHide  : true,
                                    autoRotate: false,
                                },
                            },
                            meta  : {
                                day  : {
                                    alias: '日期',
                                },
                                total: {
                                    alias: '活跃用户数',
                                },
                            },
                        });
                        columnPlot.render();
                    }
                }
            })
        }
    }

    return Controller;
})